package com.maiyuren.fishkit.ui.pages.main

import android.annotation.SuppressLint
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.KeyboardArrowDown
import androidx.compose.material.icons.outlined.KeyboardArrowUp
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.navigation.NavHostController
import com.maiyuren.fishkit.dict.FishDictMgr
import com.maiyuren.fishkit.history.FavouriteManager
import com.maiyuren.fishkit.history.HistoryManager
import com.maiyuren.fishkit.ui.components.FishIconButton
import com.maiyuren.fishkit.ui.components.FishMenu
import com.maiyuren.fishkit.ui.components.FishSearchTextField
import com.maiyuren.fishkit.ui.components.dict.DictGroupPage
import com.maiyuren.fishkit.ui.theme.lightColor
import com.maiyuren.fishkit.utils.FishStorage

private var vm = MainPageViewModel()
internal val titleBarHeight = 48.dp;
internal val bottomBarHeight = 56.dp

@RequiresApi(Build.VERSION_CODES.Q)
@Composable
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "UnrememberedMutableState")
fun HomePage(navController: NavHostController?) {
    vm.navController = navController

    Box(modifier = Modifier.fillMaxSize()) {
        TitleBar()
        Column(modifier = Modifier.fillMaxSize()) {
            Column(modifier = Modifier.weight(1.0f)) {
                contentView()
            }
            Column() {
                BottomBar()
            }
        }

        // 因缘会字
        AnimatedVisibility(
            modifier = Modifier
                .offset(0.dp, -100.dp)
                .align(Alignment.BottomCenter),
            visible = vm.showRandomUI.value,
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Icon(
                    modifier = Modifier.clickable {
                        vm.showRandomUI.value = false
                    },
                    imageVector = Icons.Outlined.Close,
                    contentDescription = null,
                    tint = Color(0x88FF0000)
                )
                Row(modifier = Modifier
                    .width(54.dp)
                    .height(54.dp)
                    .background(
                        color = MaterialTheme.colorScheme.background,
                        shape = RoundedCornerShape(percent = 50)
                    ),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    FishIconButton(
                        icon = "\uE6FD",
                        onClick = { vm.goRandomWord() })
                }
            }
        }

        // 搜寻痕迹
        AnimatedVisibility(
            modifier = Modifier
                .offset(0.dp, -bottomBarHeight)
                .height(32.dp)
                .align(Alignment.BottomCenter)
                .fillMaxWidth(),
            visible = vm.showHistoryUI.value,
        ) {
            LazyRow(
                modifier = Modifier
                    .border(width = 1.dp, color = Color.Black, shape = RoundedCornerShape(8.dp))
                    .background(color = lightColor),
                verticalAlignment = Alignment.CenterVertically
            ) {
                items(HistoryManager.instance().words_.size) {
                    val txt = HistoryManager.instance().words_[it]!!
                    Text(
                        modifier = Modifier
                            .padding(horizontal = 8.dp)
                            .clickable {
                                vm.toSearchText.value = txt
                                vm.onSearch()
                            },
                        text = txt
                    )
                }
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.Q)
@Composable
private fun TitleBar() {
    Row(
        modifier = Modifier
            .height(height = titleBarHeight)
            .fillMaxWidth()
            .zIndex(1F)
    ) {
        val favouriteIcon = if (vm.isCurrSearchWordFavourite.value) "\uE634" else "\uE62D"
        FishIconButton(icon = favouriteIcon,
            enabled = vm.isCurrFound.value,
            fontSize = 28.sp) {
            if (!vm.isCurrSearchWordFavourite.value) {
                FavouriteManager.instance().add(vm.currFoundWord.value)
                vm.isCurrSearchWordFavourite.value = true
            } else {
                FavouriteManager.instance().delete(vm.currFoundWord.value)
                vm.isCurrSearchWordFavourite.value = false
            }
        }

        Spacer(modifier = Modifier.weight(1F))


        FishIconButton(icon = "\uE600") {
            var currIndex = 0;
            for (i in 0 until FishDictMgr.groups.size) {
                if (FishDictMgr.groups[i].id == vm.currGroupId.value) {
                    currIndex = i;
                    break;
                }
            }
            currIndex += 1
            currIndex %= FishDictMgr.groups.size;
            vm.currGroupId.value = FishDictMgr.groups[currIndex].id;
            vm.delaySearch(1000)
            FishStorage.setString(FishStorage.keys.curr_dict_group_id, vm.currGroupId.value)
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@RequiresApi(Build.VERSION_CODES.Q)
@Composable
private fun BottomBar() {
    Row(
        modifier = Modifier
            .height(height = bottomBarHeight)
            .fillMaxWidth()
            .padding(PaddingValues(end = 8.dp)),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // menu
        Row {
            FishMenu(
                offset = DpOffset(x = 4.dp, y = 0.dp),
                data = vm.mainMenu,
                visible = vm.showMainMenu)

            FishIconButton(icon = "\uE652") {
                vm.showMainMenu.value = !vm.showMainMenu.value
            }
        }


        // history
        Box(modifier = Modifier
            .padding(PaddingValues(horizontal = 8.dp, vertical = 2.dp))
            .height(48.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            val icon = if (vm.showHistoryUI.value) Icons.Outlined.KeyboardArrowDown else Icons.Outlined.KeyboardArrowUp
            Icon(
                modifier = Modifier
                    .size(20.dp)
                    .padding(0.dp),
                imageVector = icon,
                contentDescription = null,
                tint = Color(0x88000000)
            )
            FishIconButton(
                modifier = Modifier.absoluteOffset(y = 14.dp),
                icon = "\uE690",
                onClick = {
                    vm.showHistoryUI.value = !vm.showHistoryUI.value
                },
                padding = PaddingValues(0.dp)
            )
        }

        // histore pre
        FishIconButton(icon = "\uE675") {
            val word = HistoryManager.instance().preWord()
            if (word != null) {
                vm.toSearchText.value = word
                vm.onSearch(false)
            }
        }

        // history next
        FishIconButton(icon = "\uE677") {
            val word = HistoryManager.instance().nextWord()
            if (word != null) {
                vm.toSearchText.value = word
                vm.onSearch(false)
            }
        }


        FishSearchTextField(
            modifier = Modifier.weight(1F),
            value = vm.toSearchText,
            onValueChange = {
                vm.toSearchText.value = it
            },
            onSearch = {
                vm.onSearch()
            }
        )

    }
}

@SuppressLint("CoroutineCreationDuringComposition")
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun contentView() {
    FishDictMgr.groups.forEachIndexed { index, item->
        AnimatedVisibility(
            visible = vm.currGroupId.value == item.id,
        ) {
            DictGroupPage(id = item.id, vm = vm)
        }
    }
}